<template>
  <x-layout-main>
    <div class="g-content">
      <n-spin :show="loading">
        <x-form ref="formRef" v-model:model="form" :rules="rules" :label-width="90" label-placement="left">
          <n-form-item label="岗位名称" path="roleName">
            <n-input v-model:value="form.roleName" maxlength="30" clearable placeholder="请输入岗位名称" show-count />
          </n-form-item>
          <n-form-item label="岗位名称" path="roleDesc">
            <n-input
              v-model:value="form.roleDesc"
              type="textarea"
              maxlength="100"
              clearable
              placeholder="请输入岗位描述"
              show-count
            />
          </n-form-item>
          <n-form-item label="权限设置" path="checkList">
            <!--          <n-data-table :data="c" :columns="columns" :pagination="false" />-->
            <n-checkbox-group v-model:value="form.checkList" style="width: 100%" @update:value="handleChangeChecked">
              <n-table class="table" size="small">
                <thead>
                  <tr>
                    <th>一级菜单</th>
                    <th>二级菜单</th>
                    <th>三级菜单</th>
                    <th>功能权限</th>
                    <th>数据权限</th>
                  </tr>
                </thead>
                <tbody v-if="tableList.length > 0" class="text-sm">
                  <template v-for="(firstItem, firstIndex) in tableList" :key="firstIndex">
                    <template v-for="(secondItem, secondIndex) in firstItem.children" :key="secondIndex">
                      <template v-for="(thirdItem, thirdIndex) in secondItem.children" :key="thirdIndex">
                        <tr>
                          <td v-if="secondIndex === 0 && thirdIndex === 0" :rowspan="calculateFirstRowSpan(firstItem)">
                            <n-checkbox
                              :value="firstItem.id"
                              :label="firstItem.resourceDescription"
                              :indeterminate="firstItem.indeterminate"
                            ></n-checkbox>
                          </td>
                          <td v-if="thirdIndex === 0" :rowspan="secondItem.children.length">
                            <n-checkbox
                              :value="secondItem.id"
                              :label="secondItem.resourceDescription"
                              :indeterminate="secondItem.indeterminate"
                            ></n-checkbox>
                          </td>
                          <td>
                            <n-checkbox
                              :value="thirdItem.id"
                              :label="thirdItem.resourceDescription"
                              :indeterminate="thirdItem.indeterminate"
                            ></n-checkbox>
                          </td>
                          <td>
                            <n-checkbox
                              v-for="(item, index) in thirdItem.children"
                              :key="index"
                              :value="item.id"
                              :label="item.resourceDescription"
                            ></n-checkbox>
                          </td>
                          <td>
                            <n-radio-group v-model:value="thirdItem.dataRange">
                              <n-radio :value="0">全部</n-radio>
                              <n-radio :value="1">个人</n-radio>
                              <n-radio :value="2">部门</n-radio>
                            </n-radio-group>
                          </td>
                        </tr>
                      </template>
                    </template>
                  </template>
                </tbody>
              </n-table>
            </n-checkbox-group>
          </n-form-item>
        </x-form>
      </n-spin>
      <div>
        <x-button :loading="loading" type="primary" @click="submitForm">保存</x-button>
        <x-button @click="handleCancel">取消</x-button>
      </div>
    </div>
  </x-layout-main>
</template>
<script setup lang="ts">
  import { XButton, XForm, XLayoutMain } from '@/components'
  import {
    NFormItem,
    NInput,
    NModal,
    NSpin,
    NDataTable,
    NSpace,
    NCheckboxGroup,
    NCheckbox,
    NRadioGroup,
    NRadio,
    NTable
  } from 'naive-ui'
  import { computed, reactive, ref, h, onMounted, watch } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { useStore } from '@/store'
  import { filterCheckedIds, getTreeItem } from '@/utils'

  const store = useStore()
  const router = useRouter()
  const route = useRoute()
  const form = ref({
    roleName: '',
    roleDesc: '',
    checkList: []
  })
  const formRef = ref(null)
  const id = route.query?.id || null
  const loading = ref(false)
  const rules = reactive({
    roleName: {
      required: true,
      message: '请输入岗位名称',
      trigger: 'blur'
    },
    roleDesc: {
      required: true,
      message: '请输入岗位名称',
      trigger: 'blur'
    },
    checkList: {
      required: true,
      validator(rule: any, value: []) {
        if (value && value.length) {
          return true
        } else {
          return new Error('请选择关联权限')
        }
      },
      trigger: 'change'
    }
  })
  const tableList = ref([
    // {
    //   id: 1,
    //   resourceName: 'settings',
    //   resourceDescription: '设置',
    //   resourceType: 1,
    //   parentId: 0,
    //   deletedFlag: 0,
    //   resourceRemark: '',
    //   dataStatus: 1,
    //   createdAt: '2021-08-04 03:58:32',
    //   platformType: 1,
    //   selected: false,
    //   children: [
    //     {
    //       id: 2,
    //       resourceName: 'resource-list',
    //       resourceDescription: '资源项管理',
    //       resourceType: 2,
    //       parentId: 1,
    //       deletedFlag: 0,
    //       resourceRemark: '',
    //       createdAt: '2021-08-04 03:59:50',
    //       platformType: 1,
    //       selected: false,
    //       children: [
    //         {
    //           id: 3,
    //           resourceName: 'resource-list',
    //           resourceDescription: '资源项管理11',
    //           resourceType: 2,
    //           parentId: 1,
    //           deletedFlag: 0,
    //           resourceRemark: '',
    //           createdAt: '2021-08-04 03:59:50',
    //           platformType: 1,
    //           selected: false,
    //           children: []
    //         }
    //       ]
    //     }
    //   ]
    // }
  ])

  const level1 = ref([])
  const level2 = ref([])
  const level3 = ref([])
  const level4 = ref([])

  onMounted(async () => {
    await getSystemAuthority()
    if (id) {
      await getDetail()
    }
  })

  // 获取资源项列表
  const getSystemAuthority = async () => {
    const { data } = await store.dispatch('system/getSystemAuthority', {
      platformType: 1
    })
    tableList.value = data || []
    level1.value = getLevels(tableList.value, 1)
    level2.value = getLevels(tableList.value, 2)
    level3.value = getLevels(tableList.value, 3)
    level4.value = getLevels(tableList.value, 4)
  }

  // 获取岗位详情
  const getDetail = async () => {
    const { data } = await store.dispatch('system/getSystemRleDetail', { roleId: id })
    tableList.value = data.resourceList || []

    const checkedData = filterCheckedIds(tableList.value)
    console.log(checkedData, 'checkedData')
    form.value.checkList = checkedData || []
  }
  // 初始化资源项数据
  function initData(data: any[]) {
    let result: any[] = []
    data.forEach((item, index) => {
      item.level = index + 1
      if (item.children && item.children.length > 0) {
        result = result.concat(initData(item.children))
      }
    })
    return data
  }
  // 展开所有列表数据
  function getLevels(data: any[], targetLevel: number, currentLevel = 1) {
    let result: any[] = []
    if (currentLevel === targetLevel) {
      return data
    }

    data.forEach((item) => {
      item.level = currentLevel
      if (item.children && item.children.length > 0) {
        result = result.concat(getLevels(item.children, targetLevel, currentLevel + 1))
      }
    })

    return result
  }

  // 获取全部select的值

  const calculateFirstRowSpan = (firstItem) => {
    return firstItem.children.reduce((acc, secondItem) => acc + secondItem.children.length, 0)
  }
  const handleChangeChecked = (val: any) => {
    console.log(level1.value)
    console.log(level2.value)
    console.log(level3.value)
    console.log(level4.value)
  }

  // 三级菜单点击
  // const thirdClick = (
  //   thirdItem: any,
  //   thirdIndex: any,
  //   secondItem: any,
  //   secondIndex: any,
  //   firstItem: any,
  //   firstIndex: any
  // ) => {
  //   // console.log(thirdItem, thirdIndex)
  //   const thirdIdList = secondItem.children.map((t) => t.id)
  //   console.log(thirdIdList, form.value.checkList)
  //   const allIds = form.value.checkList
  //   // 当前id集是否都被选中
  //   const isSecondCheckedAll = thirdIdList.every((i) => allIds.includes(i))
  //   console.log(isSecondCheckedAll, 222)
  //   if (isSecondCheckedAll) {
  //     form.value.checkList.push(secondItem.id)
  //     let arrNew = Array.from(new Set(allIds))
  //     form.value.checkList = arrNew
  //     secondItem.indeterminate = false
  //   } else {
  //     secondItem.indeterminate = true
  //   }
  // }
  // const thirdClick = (thirdItem: any) => {
  //   // 递归查找他的父元素
  //   if (thirdItem.parentId) {
  //     const parentItem = findParentElement(tableList.value, thirdItem.id)
  //     console.log(parentItem, 111)
  //   }
  // }
  // // 查找父元素
  // const findParentElement = (data: any, id: any, parent = null) => {
  //   for (let element of data) {
  //     if (element.id === id) {
  //       return parent
  //     }
  //     if (element.children && element.children.length > 0) {
  //       let result = findParentElement(element.children, id, element)
  //       if (result) {
  //         return result
  //       }
  //     }
  //   }
  //   return null
  // }

  // // 更新节点的 indeterminate 状态
  // const updateIndeterminate = (item) => {
  //   if (item.children && item.children.length > 0) {
  //     const checkedChildren = item.children.filter((child) => form.value.checkList.includes(child.id))
  //     item.indeterminate = checkedChildren.length > 0 && checkedChildren.length < item.children.length
  //     item.checked = checkedChildren.length === item.children.length
  //
  //     item.children.forEach((child) => updateIndeterminate(child))
  //   }
  // }
  //
  // // 处理 checkbox 的变更事件
  // const handleChange = (item) => {
  //   if (item.children && item.children.length > 0) {
  //     item.children.forEach((child) => {
  //       if (form.value.checkList.includes(item.id)) {
  //         if (!form.value.checkList.includes(child.id)) {
  //           form.value.checkList.push(child.id)
  //         }
  //       } else {
  //         const index = form.value.checkList.indexOf(child.id)
  //         if (index > -1) {
  //           form.value.checkList.splice(index, 1)
  //         }
  //       }
  //       handleChange(child)
  //     })
  //   }
  //   updateIndeterminate(item)
  //   updateParentIndeterminate(item)
  // }
  //
  // // 更新父节点的 indeterminate 状态
  // const updateParentIndeterminate = (item) => {
  //   if (item.parent) {
  //     const parent = item.parent
  //     const checkedChildren = parent.children.filter((child) => form.value.checkList.includes(child.id))
  //     parent.indeterminate = checkedChildren.length > 0 && checkedChildren.length < parent.children.length
  //     parent.checked = checkedChildren.length === parent.children.length
  //
  //     updateParentIndeterminate(parent)
  //   }
  // }
  //
  // // 初始化数据结构时，设置父子关系
  // const initializeParents = (items, parent = null) => {
  //   items.forEach((item) => {
  //     item.parent = parent
  //     if (item.children && item.children.length > 0) {
  //       initializeParents(item.children, item)
  //     }
  //   })
  // }
  //
  // // 初始化表格数据
  // initializeParents(tableList.value)
  // watch(
  //   () => form.value.checkList,
  //   (val) => {
  //     tableList.value.forEach((item) => {
  //       updateIndeterminate(item)
  //     })
  //   },
  //   {
  //     immediate: true
  //   }
  // )
  const submitForm = () => {
    formRef.value?.validate(async (errors) => {
      if (!errors) {
        const params = {
          id: id,
          roleName: form.value.roleName,
          roleDesc: form.value.roleDesc,
          dataRangeList: [
            {
              resourceId: [],
              dataRange: 1
            }
          ]
        }
        console.log(params, 'save')
        store.dispatch('system/getSystemRleSave', params)
      }
    })
  }
  const handleCancel = () => {
    router.back()
  }
</script>
<style scoped lang="scss"></style>
